package com.emser.unc.client.presenter;

import com.emser.unc.client.CloudMobile;
import com.emser.unc.client.helper.RPCCall;
import com.emser.unc.client.service.SellerService;
import com.emser.unc.client.service.SellerServiceAsync;
import com.emser.unc.serializable.LocationDTO;
import com.emser.unc.serializable.UserAccountDTO;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

public class MapGeolocationPresenter implements Presenter{
	private final Display display; 
	private String serialDevice;
	private SellerServiceAsync rpcSellerService;
	private UserAccountDTO userA;
	
	public interface Display {	
	    Widget asWidget(); 
	    void updatePosM(double latitud, double longitud, String title);
	  }
	
	public MapGeolocationPresenter(Display display, String serialDevice,UserAccountDTO user){
		this.display = display;
		this.serialDevice = serialDevice;
		this.rpcSellerService = GWT.create(SellerService.class);
		this.userA = user;
		showLocation();
	}
	
	private void showLocation(){
		getLocation();
		if(CloudMobile.get().getT() != null)
			CloudMobile.get().getT().cancel();
		Timer t = new Timer() {
		public void run() {
			getLocation();
		}
		};
		t.scheduleRepeating(10000);
		CloudMobile.get().setT(t);
	}


	private void getLocation() {
		new RPCCall<LocationDTO>(){
			@Override
			public void onFailure(Throwable caught) {
				Window.alert(CloudMobile.constants.eGetSerialDevices());
				CloudMobile.get().getT().cancel();
			}

			@Override
			public void onSuccess(LocationDTO location) {
				if((location != null) && (location.getLatitude()!= null) && (location.getLongitude() != null)){
					display.updatePosM(location.getLatitude(), location.getLongitude(),location.getFirstName()+" "+location.getLastName());
				}
			}
			@Override
			protected void callService(AsyncCallback<LocationDTO> cb) {
				rpcSellerService.getLocation(serialDevice,userA.getName(), cb);
			}
		}.retry(1);		
	}


	public void go(HasWidgets container) {
		container.clear();
	    container.add(display.asWidget());
	}
}
